#!/bin/bash

TMP_BRANCH="$(date +%s)";

# Ordered branches to create patches from
BRANCHES=("misc" \
          "openexr" \
          "opencollada" \
          "openvdb" \
          "oiio" \
          "cycles" \
          "python3.7" \
          "python3.8" \
          "python3.9" \
          "python3.10" \
          "python3.11" \
          "python3.12" \
          "ffmpeg");

PATCHES=("0000_misc.patch" \
         "0001_openexr3.patch" \
         "0002_opencollada1_6_68.patch" \
         "0003_openvdb.patch" \
         "0004_openimageio.patch" \
         "0005_cycles.patch" \
         "0006_python3_7.patch" \
         "0007_python3_8.patch" \
         "0008_python3_9.patch" \
         "0009_python3_10.patch" \
         "0010_python3_11.patch" \
         "0011_python3_12.patch" \
         "0012_ffmpeg.patch")

if [[ -f ".creating_patches" ]]; then
  echo "Creating patches already active, maybe there was a merge conflict?";
  exit 1;
fi


# Create a new TMP branch from vanilla source
git checkout master;
git branch "${TMP_BRANCH}";
git checkout "${TMP_BRANCH}";

# Merge branches into our TMP branch and created patches while doing so
for i in ${!BRANCHES[@]}; do
  branch="${BRANCHES[${i}]}"
  patch="${PATCHES[${i}]}"

  # Write git log for branch
  git checkout "${branch}"
  git log master.."${branch}" > "patches/${patch}"
  echo "" >> "patches/${patch}"
  git checkout "${TMP_BRANCH}"

  # Merge branch
  git merge "${branch}" --no-ff -m "Merge branch ${branch} into ${TMP_BRANCH}";

  # Merge conflict
  if [[ $? -ne 0 ]]; then
    conflicting=$(git diff --name-only --diff-filter=U --relative)
    while [ -n "${conflicting}" ]; do
      echo "The following files have conflict(s):"
      echo "-----------------------------------"
      echo "${conflicting}"
      echo "-----------------------------------"
      read -p "Please resolve the conflict(s), stage the resolved file(s) and press any key to continue."
      conflicting=$(git diff --name-only --diff-filter=U --relative)
    done
    git commit -m "Merge branch ${branch} into ${TMP_BRANCH}";
  fi

  # Create patch
  git diff HEAD^ HEAD >> "patches/${patch}"
done

# Checkout master branch so we can delete the TMP branch
git checkout master

# Delete TMP branch
git branch -D "${TMP_BRANCH}"
